package com.git.smp.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.git.smp.entity.SmpField;
import com.git.smp.entity.SmpSystemCallExtend;

public class FieldUtil {
	static Logger logger = LoggerFactory.getLogger(FieldUtil.class);
	public static Document fieldToXml(List<SmpField> listField,SmpSystemCallExtend smpSystemCallExtend) {
		
		Document doc = DocumentHelper.createDocument();
		doc.addComment(smpSystemCallExtend.getTransName());
		Element Transaction = doc.addElement("Transaction");
		
		Random random = new Random();
	

		//构建标准报文头
		Element Header = Transaction.addElement("Header");
		Element sysHeader = Header.addElement("sysHeader");
		sysHeader.addComment("全局流水号（作为全行所有系统的唯一标识，各系统保证系统内唯一性；\r\n"
				+ "格式：3位应用系统编码(若未分配渠道号，请使用所属中间业务平台的渠道号)+8位日期(YYYYMMDD)+2位应用节点号+10位流水号+3位接力流水号+6位保留字段；\r\n"
				+ "前23位由业务原始发起方生成，派生的交易不允许改变；2位应用节点号从01开始递增的数字；3位接力流水由001开始，依次递增；6位保留字段默认为6个0。备注：接力流水号见详细说明。）");
		Element globalSq = sysHeader.addElement("globalSq");
		
		String global = smpSystemCallExtend.getPubSysCode().substring(0, 3);
		global+=new SimpleDateFormat("yyyyMMdd").format(new Date());
		global+="01";
		
		global+=String.format("%010d", random.nextInt(999999999)+1);
		global+="001000000";
		
		globalSq.setText(global);//全局流水号
		sysHeader.addComment("服务编码");
		Element servCd = sysHeader.addElement("servCd");//P值
		servCd.setText(smpSystemCallExtend.getPubCode());
		sysHeader.addElement("pinIndex");
		sysHeader.addElement("bizResText");
		sysHeader.addElement("extend");
		sysHeader.addElement("authPara");
		Element msgDate = sysHeader.addElement("msgDate");
		msgDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		Element msgTime = sysHeader.addElement("msgTime");
		msgTime.setText(new SimpleDateFormat("HH.mm.ss.SSS").format(new Date()));
		sysHeader.addComment("服务系统编码");
		Element serverCd = sysHeader.addElement("serverCd");
		serverCd.setText(smpSystemCallExtend.getRegSysCode());
		sysHeader.addElement("pinValue");
		Element operation = sysHeader.addElement("operation");
		operation.setText(smpSystemCallExtend.getTransCode());
		 sysHeader.addElement("authContext");
		sysHeader.addComment("交易码");
		Element tranCode = sysHeader.addElement("tranCode");
		tranCode.setText(smpSystemCallExtend.getTransCode());
		sysHeader.addElement("authId");
		Element termCd = sysHeader.addElement("termCd");
		termCd.setText("127.0.0.1=88-A8-B8-C8-D8-E8");
		sysHeader.addComment("请求系统编码");
		Element sysCd = sysHeader.addElement("sysCd");
		sysCd.setText(smpSystemCallExtend.getPubSysCode());
		 sysHeader.addComment("消息流水号（全行各系统内对应的唯一流水号，一般由服务请求者生成，各系统保证系统内唯一性。标识唯一一笔报文，用于记录、跟踪消息处理过程。不可作为渠道流水号。3位应用系统号(见附录7.4,若未分配渠道号，请使用所属中间业务平台的渠道号)+日期(YYYYMMDD)+时间(hhmmss)+流水号(1~19位)）");
		Element msgIdElement = sysHeader.addElement("msgId");
		String msgId = smpSystemCallExtend.getPubSysCode().substring(0, 3);
		msgId+=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		msgId+="01";
		msgId+=String.format("%010d", random.nextInt(999999999)+1);
		msgIdElement.setText(msgId);//全局流水号
		 sysHeader.addElement("resCd");
		 sysHeader.addElement("bizType");
		 sysHeader.addElement("bizResCd");
		 sysHeader.addElement("resText");
		 sysHeader.addComment("业务主键");
		Element bizId = sysHeader.addElement("bizId");
		bizId.setText(smpSystemCallExtend.getTransCode());
		Element orgCd = sysHeader.addElement("orgCd");
		if(smpSystemCallExtend.getRouteOrg()!=null) {
			orgCd.setText(smpSystemCallExtend.getRouteOrg());
		}
		
		Element RequestBody = Transaction.addElement("Body");
		Element request = RequestBody.addElement("request");	
		Element RequestBizHeader = request.addElement("bizHeader");
		Element RequestBizBody = request.addElement("bizBody");

		try {
			createElement(RequestBizHeader, listField, "01", "01","");
			createElement(RequestBizBody, listField, "02", "01","");
			//createElement(ResponseBizHeader, listField, "01", "02","");
			//createElement(ResponseBizBody, listField, "02", "02","");
		}catch(Exception e) {
			logger.error("导出失败",e);
		}
		return doc;
	}
	private static void createElement(Element e1, List<SmpField> listField, String struct, String inOut,String parent) {
		
		for(SmpField smpField : listField) {
			if(smpField.getParentType()==null) {
				smpField.setParentType("");
			}
			if(struct.equals(smpField.getStruct())&& inOut.equals(smpField.getInOut()) && parent.equals(smpField.getParentType())) {
				if("01".equals(smpField.getNodeType())) {
					e1.addComment(smpField.getFieldName());
					Element element = e1.addElement(smpField.getFieldCode());
					element.setText("--");
					
				}else if("03".equals(smpField.getNodeType())) {
					Element element = e1.addElement(smpField.getFieldCode());
					createElement(element, listField, struct, inOut,smpField.getFieldCode());
				}else if("02".equals(smpField.getNodeType())) {
					Element element = e1.addElement(smpField.getFieldCode());
					createElement(element, listField, struct, inOut,smpField.getFieldCode());
					createElement(element, listField, struct, inOut,smpField.getFieldCode());
				}
			}
		}
	} 
	
	
public static Map fieldToJson(List<SmpField> listField,SmpSystemCallExtend smpSystemCallExtend) {
		
		Map root = new HashMap<>();
		Map transaction = new HashMap<>();
		root.put("Transaction", transaction);
		Random random = new Random();
		//构建标准报文头
		Map Header = new HashMap<>();
		transaction.put("Header", Header);
		Map sysHeader = new HashMap<>();
		Header.put("sysHeader", sysHeader);
		String globalSq = smpSystemCallExtend.getPubSysCode().substring(0, 3);
		globalSq+=new SimpleDateFormat("yyyyMMdd").format(new Date());
		globalSq+="01";
		globalSq+=String.format("%010d", random.nextInt(999999999)+1);
		globalSq+="001000000";
		sysHeader.put("globalSq", globalSq);
		sysHeader.put("servCd", smpSystemCallExtend.getPubCode());
		sysHeader.put("pinIndex", "");
		sysHeader.put("bizResText", "");
		sysHeader.put("extend", "");
		sysHeader.put("authPara", "");
		sysHeader.put("msgDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		sysHeader.put("msgTime",new SimpleDateFormat("HH.mm.ss.SSS").format(new Date()));
		sysHeader.put("serverCd", smpSystemCallExtend.getRegSysCode());
		sysHeader.put("pinValue", "");
		sysHeader.put("operation", smpSystemCallExtend.getTransCode());
		sysHeader.put("authContext", "");
		sysHeader.put("tranCode", smpSystemCallExtend.getTransCode());
		sysHeader.put("authId", "");
		sysHeader.put("termCd", "127.0.0.1=88-A8-B8-C8-D8-E8");
		sysHeader.put("sysCd",smpSystemCallExtend.getPubSysCode());
		String msgId = smpSystemCallExtend.getPubSysCode().substring(0, 3);
		msgId+=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		msgId+="01";
		msgId+=String.format("%010d", random.nextInt(999999999)+1);
		sysHeader.put("msgId",msgId);
		sysHeader.put("resCd","");
		sysHeader.put("bizType","");
		sysHeader.put("bizResCd","");
		sysHeader.put("resText","");
		sysHeader.put("bizId",smpSystemCallExtend.getTransCode());
		if(smpSystemCallExtend.getRouteOrg()!=null) {
			sysHeader.put("orgCd",smpSystemCallExtend.getRouteOrg());
		}else {
			sysHeader.put("orgCd","");
		}
		Map body = new HashMap<>();
		transaction.put("Body", body);
		Map request = new HashMap<>();
		body.put("request", request);
		Map bizHeader = new HashMap<>();
		Map bizBody = new HashMap<>();
		try {
			createMap(bizHeader, listField, "01", "01","");
			createMap(bizBody, listField, "02", "01","");
			//createElement(ResponseBizHeader, listField, "01", "02","");
			//createElement(ResponseBizBody, listField, "02", "02","");
		}catch(Exception e) {
			logger.error("导出失败",e);
		}
		if(bizHeader.isEmpty()) {
			request.put("bizHeader", "");
		}else {
			request.put("bizHeader", bizHeader);
		}
		request.put("bizBody", bizBody);
		
		
		return root;
	}
	private static void createMap(Map map, List<SmpField> listField, String struct, String inOut,String parent) {
		
		for(SmpField smpField : listField) {
			if(smpField.getParentType()==null) {
				smpField.setParentType("");
			}
			if(struct.equals(smpField.getStruct())&& inOut.equals(smpField.getInOut()) && parent.equals(smpField.getParentType())) {
				if("01".equals(smpField.getNodeType())) {//单节点
					
					map.put(smpField.getFieldCode(),"02".equals(smpField.getFieldType())?0:"");
					
					/*
					 * Element element = e1.addElement(smpField.getFieldCode());
					 * e1.addComment(smpField.getFieldName()); element.setText("--");
					 */
					
					
				}else if("03".equals(smpField.getNodeType())) {//List节点
					
					Map list = new HashMap<>();
					map.put(smpField.getFieldCode(), list);
					
					createMap(list, listField, struct, inOut,smpField.getFieldCode());
				}else if("02".equals(smpField.getNodeType())) {//Detail节点
					List detail = new ArrayList<>();
					Map detailMap = new HashMap<>();
					detail.add(detailMap);
					map.put(smpField.getFieldCode(), detail);
					createMap(detailMap, listField, struct, inOut,smpField.getFieldCode());
					
					/*
					 * Element element = e1.addElement(smpField.getFieldCode());
					 * createElement(element, listField, struct, inOut,smpField.getFieldCode());
					 * createElement(element, listField, struct, inOut,smpField.getFieldCode());
					 */
				}
			}
		}
	} 
	
}
